<?php
namespace JwtSsoSdk;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtSsoSdk {
    private $secretKey;
    private $issuer;
    private $audience;

    public function __construct($secretKey, $issuer, $audience) {
        $this->secretKey = $secretKey;
        $this->issuer = $issuer;
        $this->audience = $audience;
    }

    public function generateToken($userId, $roleId, $name) {
        $payload = [
            "iss" => $this->issuer,
            "aud" => $this->audience,
            "iat" => time(),
            "exp" => time() + (60 * 60),
            "user_id" => $userId,
            "role_id" => $roleId,
            "name" => $name
        ];
        return JWT::encode($payload, $this->secretKey, 'HS256');
    }

    public function validateToken($token) {
        try {
            $decoded = JWT::decode($token, new Key($this->secretKey, 'HS256'));
            if ($decoded->iss !== $this->issuer || $decoded->aud !== $this->audience) {
                return false;
            }
            return [
                'user_id' => $decoded->user_id,
                'role_id' => $decoded->role_id,
                'name' => $decoded->name
            ];
        } catch (\Exception $e) {
            return false;
        }
    }

    public function getTokenFromHeader() {
        $headers = apache_request_headers();
        if (isset($headers['Authorization'])) {
            return str_replace('Bearer ', '', $headers['Authorization']);
        }
        return null;
    }
}